package com.basic.thread;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

import com.beans.QueueModel;

public class ThreadTest {

	/**
	 * @Title: main @Description: TODO(这里用一句话描述这个方法的作用) @param @param args
	 *         设定文件 @return void 返回类型 @throws
	 */
	public static void main(String[] args) {
		callableTest();

	}

	/**
	 * @Title: productAndConsum
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * 
	 * @param 设定文件
	 * 
	 * @return void 返回类型
	 * 
	 * @throws
	 */
	public static void productAndConsum() {
		ProductConsum productConsum = new ProductConsum();
		Thread thread1 = new Thread(new ProductThread(productConsum));
		Thread thread2 = new Thread(new ConsumThread(productConsum));
		try {
			thread1.setName("ProductThread");
			thread1.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
				public void uncaughtException(Thread t, Throwable e) {
					System.out.println(t.getName() + "occur error");
				}
			});
			thread1.start();
			thread2.setName("ConsumThread");
			thread2.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
				public void uncaughtException(Thread t, Throwable e) {
					System.out.println(t.getName() + "occur error");
				}
			});
			thread2.start();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * @Title: callableTest @Description: TODO(这里用一句话描述这个方法的作用) @param: @return:
	 *         void @throws
	 */
	public static void callableTest() {
		MyCallable td = new MyCallable();

		// 1.执行 Callable 方式，需要 FutureTask 实现类的支持，用于接收运算结果。
		FutureTask<Integer> result = new FutureTask<Integer>(td);

		new Thread(result).start();

		// 2.接收线程运算后的结果
		try {
			Integer sum = result.get(); // FutureTask 可用于 闭锁
										// 类似于CountDownLatch的作用，在所有的线程没有执行完成之后这里是不会执行的
			System.out.println(sum);
			System.out.println("------------------------------------");
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}

	static ReentrantLock r = new ReentrantLock();

	/**@Title: lockTest   
	* @Description: TODO(这里用一句话描述这个方法的作用)   
	* @param:       
	* @return: void      
	* @throws   
	*/
	private static void lockTest() {
		ReentrantLock lock = new ReentrantLock();

		ReentrantReadWriteLock lock1 = new ReentrantReadWriteLock();
		ReadLock r = lock1.readLock();
		r.lock();
		r.unlock();
		WriteLock w = lock1.writeLock();
		w.lock();
		w.unlock();
	}
}
